#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
中间件
"""

from flask import request, g
from flask_jwt_extended import get_jwt_identity, verify_jwt_in_request
from models import User, db
from datetime import datetime
import logging

logger = logging.getLogger(__name__)

def update_user_activity():
    """更新用户活动时间"""
    try:
        # 检查是否有有效的JWT token
        verify_jwt_in_request(optional=True)
        user_id = get_jwt_identity()
        
        if user_id:
            # 更新用户的最后活动时间
            user = User.query.get(user_id)
            if user:
                user.last_activity = datetime.utcnow()
                db.session.commit()
                
    except Exception as e:
        # 如果更新失败，记录日志但不影响正常请求
        logger.debug(f"更新用户活动时间失败: {e}")

def register_middleware(app):
    """注册中间件"""
    
    @app.before_request
    def before_request():
        """请求前处理"""
        # 更新用户活动时间
        update_user_activity()
